package org.http;

import org.http.exp.TinyException;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author andy
 */
public class HandleHeader {

    public Headers parseHeader(String headerStr){

        if (Objects.isNull(headerStr) || headerStr.isEmpty()) {
            throw new TinyException();
        }

        int index = headerStr.indexOf(Const.CRLF);
        if (index == -1) {
            throw new TinyException();
        }

        Headers headers = new Headers();
        String firstLine = headerStr.substring(0, index);
        String[] parts = firstLine.split(" ");

        /***
         * 请求头的第一行必须由三部分构成，分别为 METHOD PATH VERSION
         * 比如： GET /index.html HTTP/1.1
         */
        if (parts.length < Const.FIRST_CONTENT_LEN) {
            throw new TinyException();
        }

        headers.setMethod(parts[0]);
        headers.setPath(parts[1]);
        headers.setVersion(parts[2]);

        parts = headerStr.split(Const.CRLF);
        String[] lastHeaders = Arrays.copyOfRange(parts,1,parts.length);
        boolean flag = false;
        for (String part : lastHeaders) {
            if (flag) {
                headers.setBody(part);
                continue;
            }
            // 除了GET，其他请求用了一个空行作为数据分隔
            if (null == part || "".equals(part)) {
                flag = true;
                continue;
            }

            index = part.indexOf(Const.KEY_VALUE_SEPARATOR);
            if (index == -1) {
                continue;
            }
            String key = part.substring(0, index);
            if (index + 1 >= part.length()) {
                headers.set(key, "");
                continue;
            }
            String value = part.substring(index + 1);
            headers.set(key, value);
        }

        return headers;
    }
}
